/*
 * GET users listing.
 */

var cname  = require('path').basename(module.filename,'.js');
var routers = require('commons-dao')(cname);
var ObjectID = require('mongodb').ObjectID;
var nodeExcel = require('excel-export');
var moment = require('moment');
var form = require('express-form');
var field = form.field;

function getRules(i18n){
    return [
       field('owner').required("", i18n.__('required','用户')),
       field('createDate').required("", i18n.__('required','操作时间')),
       field('actionurl').required("", i18n.__('required','操作URL')),
       field('remark').required("", i18n.__('required','备注')),
    ];
}


module.exports = function(app,i18n){

    routers.init(app,getRules(i18n));


    function doxls(res,docs){

        var conf ={};
        conf.stylesXmlFile = "config/xlsstyles.xml";
        conf.cols = [{
            caption:'操作人',
            type:'string',
            beforeCellWrite:function(row, cellData){
                return cellData;
            },
            width:15
        },{
            caption:'操作日期',
            type:'string',
            beforeCellWrite:function(row,cellData){
                // console.log(cellData);
                return cellData;
                //return moment(cellData).format("YYYY-MM-DD HH:mm:ss");
            },
            width:25
        },{
            caption:'行为',
            type:'string',
            width:50
        },{
            caption:'备注',
            type:'string'
        }];
        conf.rows = [];
        for(var d in docs){

            var doc = docs[d];
            conf.rows.push([
                doc.owner,
                //moment(doc.createDate, "YYYY-MM-DD HH:mm Z"),
                moment(doc.createDate).format("YYYY-MM-DD HH:mm:ss"),
                doc.actionurl,
                doc.remark
            ]);
        }
        var result = nodeExcel.execute(conf);
        res.setHeader('Content-Type', 'application/vnd.openxmlformats');
        res.setHeader("Content-Disposition", "attachment; filename=" + "Report.xlsx");
        res.end(result, 'binary');

    }


    function exportXls(req,res,collection,db){
        collection.find().toArray(function(err, docs) {
            doxls(res,docs);
            db.close();
        })
    }


    app.get('/'+cname+'/export',function(res,req){
         routers.exterior(res,req,exportXls);
    });
}







